package com.aaa.sys.controller;

import com.aaa.sys.entity.TabMenu;
import com.aaa.sys.entity.TabTree;
import com.aaa.sys.entity.TabUser;
import com.aaa.sys.service.TabMenuService;
import com.aaa.sys.service.impl.TabMenuServiceImpl;
import com.aaa.util.LayData;
import com.aaa.util.PrintJsonData;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;
import java.util.List;

@WebServlet(name = "TabManuServlet", value = "/TabManuServlet")
public class TabManuServlet extends HttpServlet {

    private TabMenuService menuService = new TabMenuServiceImpl();

    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        // 
        String method = req.getParameter("method");
        if (method==null){
           queyHtml(req,resp);
        }else if(method.equals("getTreeData")) {
            // 获取树形菜单需要的数据
            getTreeData(req,resp);
            return;

        }else if(method.equals("query")){
            query(req,resp);
            return;
        }else if(method.equals("add")){
            add(req,resp);
            return;
        }else if(method.equals("upd")){
            upd(req,resp);
            return;
        }else if(method.equals("del")){
            del(req,resp);
            return;
        }

    }

    private void getTreeData(HttpServletRequest req, HttpServletResponse resp) {
        // 获取树形菜单需要的数据
        List<TabTree> tabMenus = menuService.queryTreeData();
        System.out.println("tabMenus11111 = " + tabMenus);
        // 返回到前端页面
        LayData success = LayData.success(tabMenus);
        PrintJsonData.printData(resp,success);
    }

    private void queyHtml(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        // 当前登录的人员的角色是什么
        HttpSession session = req.getSession();
           TabUser tabUser = (TabUser) session.getAttribute("user");
        Integer rid = tabUser.getRid();
        System.out.println("当前的登陆人的rid = " + rid);

        // 根据当前登录人的角色去查找对应的菜单

        // 查询所有的数据   将数据存放到一个域里面   req session
        List<TabMenu> tabMenus = menuService.queryByRid(rid);
        req.setAttribute("menus",tabMenus);
        System.out.println("tabMenus = " + tabMenus);
        // main.jsp
        req.getRequestDispatcher("views/main.jsp").forward(req,resp);

    }

    private void del(HttpServletRequest req, HttpServletResponse resp) {
    }

    private void upd(HttpServletRequest req, HttpServletResponse resp) {
    }

    private void add(HttpServletRequest req, HttpServletResponse resp) {
    }

    private void query(HttpServletRequest req, HttpServletResponse resp) {
        List<TabMenu> tabMenus = menuService.queryAll(null);
        // 数据
        LayData success = LayData.success(tabMenus);
        PrintJsonData.printData(resp,success);
    }
}
